package com.yunquan.ohana.ui.calendar.lists.list

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.LifecycleOwner
import com.google.gson.Gson
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.base.binding.command.BindingAction
import com.yunquan.ohana.base.binding.command.BindingCommand
import com.yunquan.ohana.base.binding.command.BindingConsumer
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.ListsEntity
import com.yunquan.ohana.entity.ListsItemEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.exception.ApiException
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import com.yunquan.ohana.ui.calendar.lists.add.ListsAddActivity
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.ToastUtils
import com.yunquan.ohana.utils.Utils
import io.reactivex.rxjava3.disposables.Disposable
import me.tatarka.bindingcollectionadapter2.ItemBinding
import okhttp3.RequestBody.Companion.toRequestBody

class ListsListViewModel(application: Application) : BaseViewModel(application) {
    val ui = SingleLiveEvent<Int>()
    val showDelete = SingleLiveEvent<Boolean>()

    var mDeviceId: String? = null
    var mData: ListsEntity? = null
    val isUserType = ObservableField<Boolean>()
    val isSelectAll = ObservableField(false)
    val btnSelectAllColor = ObservableField<Int>()
    val btnSelectAllTxtColor = ObservableField<Int>()
    val selectedCount = ObservableField<String>()
    val title = ObservableField<String>()
    val content = ObservableField<String>()
    val isShowSelected = ObservableField<Boolean>()
    val isShowComplete = ObservableField<Boolean>()
    val mDataList = mutableListOf<ListsListItemViewModel>()
    val items = ObservableArrayList<ListsListItemViewModel>()
    val itemBinding = ItemBinding.of<ListsListItemViewModel>(
        BR.listsListItemViewModel,
        R.layout.item_lists_list,
    )

    val onSelectedClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val b = isShowSelected.get() ?: false
            isShowSelected.set(!b)
            items.forEach {
                it.setSelected(isShowSelected.get()!!)
            }
        }
    })

    val onSelectAllClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val b = isSelectAll.get() ?: false
            if (b) {
                selectedCount.set("0")
                btnSelectAllColor.set(Utils.instance.context.getColor(R.color.c_F6))
                btnSelectAllTxtColor.set(Utils.instance.context.getColor(R.color.c_20))
                isSelectAll.set(false)
                items.forEach {
                    it.setChecked(false)
                }
            } else {
                selectedCount.set(items.size.toString())
                btnSelectAllColor.set(Utils.instance.context.getColor(R.color.c_FF9932))
                btnSelectAllTxtColor.set(Utils.instance.context.getColor(R.color.white))
                isSelectAll.set(true)
                items.forEach {
                    it.setChecked(true)
                }
            }
            ui.value = 0
        }
    })
    val onEditListsClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val bundle = Bundle()
            bundle.putString("deviceId", mDeviceId)
            bundle.putBoolean("userType", isUserType.get() ?: false)
            bundle.putString("data", Gson().toJson(mData))
            startActivityResult(ListsAddActivity::class.java, bundle)
        }
    })
    val onCompleteClick = BindingCommand(object : BindingConsumer<Boolean> {
        override fun call(t: Boolean) {
            isShowComplete.set(t)
            items.clear()
            if (t) {
                items.addAll(mDataList.filter { it.data.type == 1 })
            } else {
                items.addAll(mDataList)
            }
        }
    })

    val onDeleteClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            val list = items.filter { it.checked.get() == true }.map { it.data }
            deleteItems(list)
        }
    })

    val onAddClick = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            createItem()
        }
    })

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        btnSelectAllColor.set(Utils.instance.context.getColor(R.color.c_F6))
        btnSelectAllTxtColor.set(Utils.instance.context.getColor(R.color.c_20))
    }

    fun changeSelected() {
        val list = items.filter { it.checked.get() == true }
        showDelete.value = list.isNotEmpty()
    }

    fun getListsItem() {
        val map = mutableMapOf<String, Any?>()
        map["listsId"] = mData?.id
        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.getListsContentByListsId(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<List<ListsItemEntity>>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: List<ListsItemEntity>?) {
                    super.onSuccess(result)
                    mDataList.clear()
                    result?.forEach {
                        mDataList.add(ListsListItemViewModel(this@ListsListViewModel, it))
                    }
                    items.clear()
                    items.addAll(mDataList)
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    fun createItem() {
        if (StringUtils.isEmpty(content.get())) {
            ToastUtils.showShort(R.string.please_enter_the_label_content)
            return
        }

        val map = mutableMapOf<String, Any?>()
        map["listsId"] = mData?.id
        map["color"] = mData?.color
        map["content"] = content.get()
        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.addListsContent(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<List<ListsItemEntity>>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: List<ListsItemEntity>?) {
                    super.onSuccess(result)
                    content.set(null)
                    items.clear()
                    result?.forEach {
                        items.add(ListsListItemViewModel(this@ListsListViewModel, it))
                    }
                }

                override fun onComplete() {
                    super.onComplete()
                    hideLoading()
                }
            })
    }

    fun deleteItems(data: List<ListsItemEntity>) {
        val map = mutableMapOf<String, Any?>()
        map["listsId"] = arrayListOf(mData?.id)
        map["deviceId"] = mDeviceId
        map["listsContentIds"] = data.map { it.id }
        val body = Gson().toJson(map).toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.deleteListsContentToId(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<Boolean>() {
                override fun onSubscribe(d: Disposable) {
                    super.onSubscribe(d)
                    showLoading()
                }

                override fun onSuccess(result: Boolean?) {
                    super.onSuccess(result)
                    if (result == true) {
                        isShowSelected.set(false)
                        selectedCount.set("0")
                        isSelectAll.set(false)
                        btnSelectAllColor.set(Utils.instance.context.getColor(R.color.c_F6))
                        btnSelectAllTxtColor.set(Utils.instance.context.getColor(R.color.c_20))
                        getListsItem()
                    } else {
                        ToastUtils.showShort(R.string.delete_failed)
                        hideLoading()
                    }
                }

                override fun onError(e: ApiException) {
                    super.onError(e)
                    hideLoading()
                }
            })
    }
}